<?php

    class ContractsController extends Controller
    {

        /**
         * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
         * using two-column layout. See 'protected/views/layouts/column2.php'.
         */
        public $layout = '//layouts/column2';

        /**
         * @return array action filters
         */
        public function filters()
        {
            return array(
                'accessControl', // perform access control for CRUD operations
                array(
                    'application.filters.RequireLoginFilter',
                ),
            );
        }

        /**
         * Specifies the access control rules.
         * This method is used by the 'accessControl' filter.
         * @return array access control rules
         */

        /**
         * Displays a particular model.
         * @param integer $id the ID of the model to be displayed
         */
        public function actionView($id)
        {
            $this->render('view', array(
                'model' => $this->loadModel($id),
            ));
        }

        /**
         * Creates a new model.
         * If creation is successful, the browser will be redirected to the 'view' page.
         */
        public function actionCreate()
        {
            $model = new Contracts();
            if (isset($_POST))
            {

                $model->attributes = $_POST;
             
                if ($model->save())
                {
                
                    echo json_encode(array(
                        'success' => true,
                        'msg' => "Saving successful",
                        'contractid' => $model->contractid
                    ));
                }
                else
                {
                    echo json_encode(array(
                        'success' => false,
                        'errors' => $model->getErrors()
                    ));
                }
            }

            Yii::app()->end();
        }

        protected function getScheduleDateFromPost($post)
        {
            $rs = array();


            if (is_array($post))
            {
                $i = 0;
                foreach ($post as $item)
                {

                    if (stripos($item['name'], '-date') !== false)
                    {
                        $rs[++$i] = $item['value'];
                    }
                }
            }
            return $rs;
        }

        public function reprocessFormParam($array)
        {
            $rs = array();
            foreach ($array as $key => $value)
            {

                $p1 = strripos($key, '[') + 1;
                $p2 = strripos($key, ']');
                if ($p2 - $p1 > 0)
                {
                    $key = substr($key, $p1, $p2 - $p1);
                    $rs[$key] = $value;
                }
                else if ($p2 == false && $p1 > 0)
                {
                    $key = substr($key, $p1);
                    $rs[$key] = $value;
                }
            }
            return $rs;
        }

        /**
         * Updates a particular model.
         * If update is successful, the browser will be redirected to the 'view' page.
         * @param integer $id the ID of the model to be updated
         */
        public function actionUpdate($contractid)
        {

            $model = $this->loadModel($contractid);
            
            outputJsByList(ContactUtil::getContactData($model->custno, $model->locno), 'contacts');
            $contractTypeList = ContractType::getListData();
            outputJsByList($contractTypeList, 'contractTypeData');
            if ($model != NULL && isset($_POST['form']))
            {
                $data = (($this->reprocessFormParam($_POST['form'])));
                $model->attributes = $data;
                $model->contractamount = $this->getContractAmount($model->contractid);
                $model->createCItem();
                $model->createHISTItem();
                $model->saveSchedulePayment();
                $scheduleData = $model->schedulePaymentModelList;
                $scheduleDataArray = array();
                //var_dump($scheduleData);exit;
                foreach ($scheduleData as $item)
                {
                    $scheduleDataArray[] = $item->attributes;
                }
                if ($model->save())
                {
                    if ($model->contractype == 4)
                    {
                        $model->createSoftHist();
                    }

                    $this->showAjaxMessage(array(
                        'schedule' => $scheduleDataArray
                            ), true);
                }
                else
                {
                    $this->showAjaxMessage(array(
                        'errors' => $model->getErrors()
                            ), true);
                }
            }
            outputJsByList(Warehouse::model()->getList(), 'warehouse');
            $billStatusList = CHtml::listData(Dropdowns::model()->findAll('type="C-BS"'), 'id', 'name');
            outputJsByList($billStatusList, 'billingStatusData');
            $contractLedger = ContractLedger::model()->findAll('contractid=:contractid', array('contractid' => $contractid));
            $planTypes = Plantypes::model()->findAll();
            $rs = array();
            foreach ($planTypes as $i => $item)
            {
                $rs[$i]['key'] = $item->id;
                $rs[$i]['value'] = $item->plantype;
            }
            Yii::app()->clientScript->registerScript('planTypes', "var planTypesData=" . json_encode($rs), CClientScript::POS_HEAD);
            $criteria = new CDbCriteria();
            $criteria->order = 'sort ASC';
            $serviceLevelList = FlOptions::model()->findAll($criteria);
            $rs = array();
            foreach ($serviceLevelList as $i => $item)
            {
                $rs[$i]['key'] = $item->id;
                $rs[$i]['value'] = $item->description;
            }
            Yii::app()->clientScript->registerScript('fl', "var serviceLevelData=" . json_encode($rs), CClientScript::POS_HEAD);
            $softwareMainRatesList = SoftwareMaintRates::model()->findAll();
            $softwareMainRatesListData = array();
            foreach ($softwareMainRatesList as $softwareMainRates)
            {
                $softwareMainRatesListData[] = $softwareMainRates->attributes;
            }
            $softwareMainRatesJson = json_encode($softwareMainRatesListData);
            Yii::app()->clientScript->registerScript('softwareMainRate', "var softwareRates  = $softwareMainRatesJson;", CClientScript::POS_HEAD);

            
            
            $list = ContractNotes::model()->findAll('contractid=:contractid', array('contractid' => $model->contractid));
            $rs = array();
            foreach ($list as $item)
            {
                $rs[] = $item->attributes;
            }
            Yii::app()->clientScript->registerScript('contractNoteData', "var contractNoteData=" . json_encode($rs), CClientScript::POS_HEAD);
            //post the tax to javascript

            $tax = Taxcode::model()->find('zipcode=:zipcode', array(
                'zipcode' => $model->location->zip
                    ));
            if ($tax == NULL)
            {
                throw new CHttpException(500, 'Please update zipcode in '
                        . CHtml::link('Location', $this->createUrl('/locations/update', array('custno' => $model->custno, 'locno' => $model->locno))));
            }
            $tax = CJSON::encode($tax->attributes);
            Yii::app()->clientScript->registerScript('tax', "
                var TAX_EXEMPT_YES=" . Locations::TAX_EXEMPT_YES . ";
                var TAX_EXEMPT_NO=" . Locations::TAX_EXEMPT_NO . ";
                var tax=$tax;
                var isExempt={$model->location->isexempt};
                ", CClientScript::POS_HEAD);

            $list = ContractEquipment::model()->findAll('contractid=:contractid', array('contractid' => $model->contractid));
            $rs = array();
            foreach ($list as $i => $item)
            {
                $rs[$i] = $item->attributes;
                $original = Equipment::model()->findByPk($item->equipmentid);
                if (isset($original))
                    $rs[$i]['description'] = $original->description;
            }
            Yii::app()->clientScript->registerScript('ContractEquipmentData', "var ContractEquipmentData=" . json_encode($rs), CClientScript::POS_HEAD);


            $this->render('update', array(
                'model' => $model,
            ));
        }

        public function actionLedgerList($contractid){
            $model = $this->loadModel($contractid);
            $itemsList = array();
            foreach ($model->ledgerList as $i => $item)
            {
                $itemsList[] = $item->attributes;
                $itemsList[$i]['price'] = $item->price;

                $itemsList[$i]['noprinttext'] = $item->getYesNoValue($item->noprint);
                $itemsList[$i]['taxedtext'] = $item->getYesNoValue($item->taxed);
            }
            if ($model->discounted)
            {
                $discount = new ContractLedger();
                $discount->price = $model->discount_percent;
                $discount->description = $model->discount_memo;
                $discount->tax1 = $model->discount_tax;
                $discount->tax2 = $model->discount_amount;
                $discount->partno = 'discount';
                $discount->warehouse = '0000';
                $itemsList[] = $discount->attributes;
            }
            $rs =array(
                'totalCount'=>count($itemsList),
                'data'=>$itemsList
            );
            echo json_encode($rs);
        }
        public function actionSaveBatchItems()
        {
            if (isset($_POST['contractid']) && isset($_POST['data']))
            {
                $contractid = $_POST['contractid'];
                $data = $_POST['data'];
                $contractModel = Contracts::model()->findByPk($contractid);

                //$data=json_decode($_POST['data']);
                //echo json_encode($data);
                foreach ($data as $item)
                {
                    if (isset($item[0]) && $item[0] == 'delete')
                    {
                        if ($item[1] == 'discount')
                        {
                            $contractModel->discounted = 0;
                            $contractModel->discount_percent = 0;
                            $contractModel->discount_memo = 0;
                            $contractModel->discount_amount = 0;
                            $contractModel->discount_tax = 0;
                            $contractModel->discount_total = 0;
                            if ($contractModel->save() === false)
                            {
                                echo "Removing discount datafailed: " . json_encode($model->getErrors());
                            }
                        }
                        else
                        {
                            $num = Yii::app()->db->createCommand()->delete('tbl_contract_ledger', 'contractid=:contractid AND id=:id', array(
                                'contractid' => $_POST['contractid'],
                                'id' => $item[1]
                                    ));
                            if ($num == 0)
                                echo "Delete failed at {$item[1]}";
                        }
                    } else
                    {

                        if (isset($item['id']) && $item['id'] != 0)
                        {

                            $model = ContractLedger::model()->findByPk(intval($item['id']));

                            $model->warehouse = $item['warehouse'];
                            $model->partno = $item['partno'];
                            $model->description = $item['description'];
                            $model->qty = $item['qty'];
                            $model->price = $item['price'];
                            $model->taxed = $item['taxed'];
                            $model->noprint = $item['noprint'];
                            $model->cost = $item['cost'];
                            $model->markupvalue = $item['markupvalue'];

                            if ($model->save() == false)
                            {
                                echo "Update failed: " . json_encode($model->getErrors());
                            }
                        }
                        else
                        {
                            if ($item['partno'] != 'discount')
                            {
                                $model = new ContractLedger;

                                //$model->attributes=$item;
                                $model->contractid = $contractid;
                                $model->warehouse = $item['warehouse'];
                                $model->partno = $item['partno'];
                                $model->description = $item['description'];
                                $model->qty = $item['qty'];
                                $model->price = $item['price'];
                                $model->taxed = $item['taxed'];
                                $model->noprint = $item['noprint'];
                                $model->cost = $item['cost'];
                                $model->markupvalue = $item['markupvalue'];
                                if ($model->save() == false)
                                {
                                    echo "Create failed: " . json_encode($model->getErrors());
                                }
                            }
                            else
                            {
                                $contractModel->discounted = 1;
                                $contractModel->discount_percent = $item['price'];
                                $contractModel->discount_memo = $item['description'];
                                $contractModel->discount_amount = $item['tax2'];
                                $contractModel->discount_tax = $item['tax1'];
                                $contractModel->discount_total = $contractModel->discount_amount + $contractModel->discount_tax;
                                if ($contractModel->save() === false)
                                {
                                    echo "Create discount datafailed: " . json_encode($model->getErrors());
                                }
                            }
                        }
                    }
                }
            }
        }

        public function actionGetContractAmount($contractid)
        {
            $sum = $this->getContractAmount($contractid);
            if ($sum !== false)
            {
                echo $sum;
                Yii::app()->end();
            }
            echo 0;
        }

        public function getContractAmount($contractid)
        {
            $contract = Contracts::model()->findByPk($contractid);
            if ($contract->contractype == 1)
            {
                $sum = Yii::app()->db->createCommand('select sum(price*qty) from tbl_contract_equipment where contractid=:contractid')
                                ->bindValues(array('contractid' => $contractid))->queryScalar();
            }
            else
            {
                $sum = Yii::app()->db->createCommand('select sum(price*qty) from tbl_contract_ledger where contractid=:contractid')
                                ->bindValues(array('contractid' => $contractid))->queryScalar();
            }

            return $sum;
        }

        public function actionSaveBatchNotes()
        {
            if (isset($_POST['contractid']) && isset($_POST['data']))
            {
                $contractid = $_POST['contractid'];
                $data = $_POST['data'];
                foreach ($data as $item)
                {
                    if (isset($item[0]) && $item[0] == 'delete')
                    {
                        Yii::app()->db->createCommand()->delete('tbl_contract_notes', 'contractid=:contractid AND id=:id', array(
                            'contractid' => $contractid,
                            'id' => $item[1],
                        ));
                    }
                    else
                    {
                        $model = NULL;
                        if (isset($item['id']) && $item['id'] != 0)
                        {

                            $model = ContractNotes::model()->findByPk($item['id']);
                            if ($model != NULL)
                            {
                                $model->dateofnote = $item['dateofnote'];
                                $model->note = $item['note'];
                                //$model->jobid=$item['jobid'];
                            }
                        }
                        else
                        {
                            $model = new ContractNotes;
                            $model->dateofnote = $item['dateofnote'];
                            $model->note = $item['note'];
                            $model->contractid = $item['contractid'];
                        }
                        if ($model != NULL)
                        {
                            $model->dateofnote = $item['dateofnote'];
                            $model->note = $item['note'];
                            if ($model->save())
                            {
                                echo 'Save successful';
                            }
                            else
                            {
                                echo json_encode($model->getErrors());
                            }
                        }
                    }
                }
            }
        }

    
        /**
         * Deletes a particular model.
         * If deletion is successful, the browser will be redirected to the 'admin' page.
         * @param integer $id the ID of the model to be deleted
         */
        public function actionCancel($contractid)
        {
            /* @var $model Contracts */

            $model = $this->loadModel($contractid);
            $custno = $model->custno;
            $locno = $model->locno;
            //$model->delete();
            //ContractLedger::model()->deleteAll('contractid=:contractid', array('contractid' => $contractid));
            //ContractNotes::model()->deleteAll('contractid=:contractid', array('contractid' => $contractid));
            $this->redirect(array('/contracts', 'custno' => $custno, 'locno' => $locno));
        }

        /**
         * Lists all models.
         */
        public function actionIndex($custno, $locno)
        {
            $jobs = new Jobs();
            $jobs->custno = $custno;
            $jobs->locno = $locno;
            $location = Locations::model()->find('custno=:custno AND locno=:locno', array(
                'custno' => $custno,
                'locno' => $locno
                    ));
            $customer = Customers::model()->findByPk($custno);
            if ($location == NULL)
                throw new CHttpException('Your request page can not found', 404);

            //adding some javascript variable;
            //jsVariableGen('Locations', 'id', array('locname','add1','city','state'), 'locations', 'custno=:custno',array('custno'=>$custno),' | ');
            outputJsByList($jobs->getBillToList(), 'locations');

            outputJsByList(SalesDepartments::model()->getListData(), 'departments');

            outputJsByList(Employees::model()->getEmployeeList(), 'employees');
            outputJsByList(Employees::model()->getSalePersonList(), 'sale');

            outputJsByList(ContractType::getListData(), 'billingstatus');


            outputJsVarible($customer->salesperson, 'defaultSalesPerson');


            //get note list

            $this->render('index', array(
                'location' => $location,
                'jobs' => $jobs
            ));
        }

        /**
         * Manages all models.
         */
        public function actionAdmin()
        {
            $model = new Contracts('search');
            $model->unsetAttributes(); // clear any default values
            if (isset($_GET['Contracts']))
                $model->attributes = $_GET['Contracts'];

            $this->render('admin', array(
                'model' => $model,
            ));
        }

      
        /**
         * Returns the data model based on the primary key given in the GET variable.
         * If the data model is not found, an HTTP exception will be raised.
         * @param integer the ID of the model to be loaded
         * @return  @var $model Contracts
         */
        public function loadModel($id)
        {
            $model = Contracts::model()->findByPk($id);
            if ($model === null)
                throw new CHttpException(404, 'The requested page does not exist.');
            return $model;
        }

        public function actionList($custno, $locno, $page = 0, $sort = NULL)
        {
            $data = CHtml::listData(ContractStatus::model()->findAll('inactive=0'), 'id', 'description');


            if ($page > 0)
                $page--;
            $order = CJSON::decode($sort);

            $data = new CActiveDataProvider('Contracts', array(
                        'criteria' => array(
                            'condition' => 'custno=:custno AND locno=:locno',
                            'params' => array(
                                'custno' => $custno,
                                'locno' => $locno,
                            ),
                            'order' => isset($order) ? $order[0]['property'] . ' ' . $order[0]['direction'] : NULL
                        ),
                        'pagination' => array(
                            'pageSize' => 20,
                            'currentPage' => $page
                        )
                    ));
            $typeList = CHtml::listData(ContractType::model()->findAll(), 'id', 'description');
            if ($data != NULL && count($data->getData()) > 0)
            {
                $rs = array();
                $rs['totalCount'] = $data->getTotalItemCount();
                foreach ($data->getData() as $i => $item)
                {

                    $rs['data'][$i] = $item->getAttributes();
                    $rs['data'][$i]['statusText'] = $item->StatusText;
                    if (isset($typeList[$item->contractype]))
                        $rs['data'][$i]['typeText'] = $typeList[$item->contractype];
                    else
                    {
                        $rs['data'][$i]['typeText'] = 'Service';
                    }
                }
                echo json_encode($rs);
            }
            Yii::app()->end();
        }

        /**
         * Performs the AJAX validation.
         * @param CModel the model to be validated
         */
        protected function performAjaxValidation($model)
        {
            if (isset($_POST['ajax']) && $_POST['ajax'] === 'contracts-form')
            {
                echo CActiveForm::validate($model);
                Yii::app()->end();
            }
        }

        public function actionPageList()
        {
            $this->render('pagelist');
        }

        public function actionListall($query=NULL, $custno=NULL, $page=NULL, $sort=NULL, $status=2,$type=null,$billingstatus=null){
            echo json_encode($this->getListAllData($query, $custno, $page, $sort, $status, $type, $billingstatus));
        }

        public function getListAllData($query=NULL, $custno=NULL, $page=NULL, $sort=NULL, $status=2,$type=null,$billingstatus=null)
        {

            $crit = new CDbCriteria();
            if ($sort != NULL)
            {
                $order = CJSON::decode($sort);
                $crit->order = $order[0]['property'] . ' ' . $order[0]['direction'];
            }
            else
            {
                $crit->order = 'CAST( SUBSTR( contractid, 1,LOCATE(  "-", contractid )-1  ) AS SIGNED) ,CAST( SUBSTR( contractid, LOCATE(  "-", contractid ) +1 ) AS SIGNED )';
            }
            $crit->alias = 'c';
            if ($query != NULL)
            {

                $crit->join = 'left join tbl_contract_type ct on ct.id= c.contractype
                         left join tbl_contract_status cs on cs.id= c.status
                         left join tbl_locations l on l.locno = c.locno and l.custno=c.custno
                         
                ';
                $crit->condition = 'l.locname=:query
                or l.state=:query or l.zip=:query or l.state=:query
                or ct.description like :like or cs.description like :like
                or c.contractstartdate =:query or c.contractid=:query
                or l.add1 like :like
                ';
                $crit->params['query'] = $query;
                $crit->params['like'] = "%$query%";
            }
            if ($custno != NULL)
            {
                $crit->addCondition('c.custno=:custno');
                $crit->params['custno'] = $custno;
            }

            if ($status != NULL)
            {
                $crit->addCondition('c.status=:status');
                    $crit->params['status'] = $status;
            }


           
            $pagination = new CPagination;
            if ($page > 0)
                $page--;
            if ($page >= 0)
            {
                $pagination->setCurrentPage($page);
                $pagination->setPageSize(20);
            }
            else
            {
                $pagination->setCurrentPage($page);
                $pagination->setPageSize(999999999); // ìninite!!!!!!!
            }
            $list = new CActiveDataProvider('Contracts', array(
                        'criteria' => $crit,
                        'pagination' => $pagination
                    ));
            $rs = array();
            if ($list != NULL && $list->getTotalItemCount() > 0)
            {

                $rs['totalCount'] = $list->getTotalItemCount();
                foreach ($list->getData() as $i => $item)
                {
                    $rs['data'][$i] = $item->attributes;
                    $rs['data'][$i]['statusText'] = $item->getStatusText();
                    $rs['data'][$i]['contracttypeText'] = ContractType::getText($item->contractype);
                    $location = $item->location;
                    if ($location != NULL)
                    {
                        $rs['data'][$i]['add1'] = $location->add1;
                        $rs['data'][$i]['locname'] = $location->locname;
                        $rs['data'][$i]['csz'] = $location->city . ' ' . $location->state . ' ' . $location->zip;
                    }
                    else
                    {
                        $rs['data'][$i]['locname'] = '';
                        $rs['data'][$i]['csz'] = '';
                    }
                    $invSum = 0;
                    $invPaidSum = 0;
                    foreach ($item->invoiceAndCMList as $invoice)
                    {
                        $invSum+= $invoice->getAmountWithDiscount();
                        $invPaidSum +=$invoice->getPaymentApplied();
                    }
                    $rs['data'][$i]['billedAmount'] = $invSum;
                    $rs['data'][$i]['paid'] = $invPaidSum;
                }
            }
            return $rs;
        }

        

        public function actionContractReport()
        {
            $data = $this->getListAllData(NULL, -1);
            $this->render('contractreport', array(
                'data' => $data
            ));
        }

        public function actionListQuote($contractid, $page = 0, $sort = NULL)
        {
            $order = CJSON::decode($sort);
            $data = new CActiveDataProvider('ContractLedger', array(
                        'criteria' => array(
                            'condition' => 'contractid=:contractid',
                            'params' => array(
                                'contractid' => $contractid,
                            ),
                            'order' => isset($order) ? $order[0]['property'] . ' ' . $order[0]['direction'] : NULL
                        ),
                        'pagination' => array(
                            'pageSize' => 20,
                            'currentPage' => $page
                        )
                    ));

            if ($data != NULL && count($data->getData()) > 0)
            {
                $rs = array();
                $rs['totalCount'] = $data->getTotalItemCount();
                foreach ($data->getData() as $i => $item)
                {

                    $rs['data'][$i] = $item->getAttributes();
                }
                echo json_encode($rs);
            }
            Yii::app()->end();
        }

        public function actionCreateScheduleInvoice($contractid)
        {
            $contract = $this->loadModel($contractid);
            $invoice = $contract->createFirstScheduleInvoice();
            if ($invoice !== false)
            {
                $this->sendInvoiceEmail($invoice);
                $this->showAjaxMessage($invoice, true);
            }
            else
            {
                $this->showAjaxMessage('Problem while create Invoice');
            }
        }

        public function sendInvoiceEmail($invoice)
        {
            $invoice = Invoice::model()->findByPk($invoice);
            $body = $this->renderPartial('invoiceEmail', array('invoice' => $invoice), true);           
            $subject = 'CC New ' . $invoice->invoicetype;
            return EmailUtil::sendEmail($subject,null,$body);
        }

        protected function checkHist(Contracts $contract)
        {
            if ($contract->contractype == 3)
            {
                $criteria = new CDbCriteria();
                $criteria->addColumnCondition(array('contractid' => $contract->contractid));
                $criteria->addColumnCondition(array('partno' => 'HIST'));
                $hist = ContractLedger::model()->find($criteria);
                if (empty($hist))
                {
                    $hist = new ContractLedger();
                    $hist->contractid = $contract->contractid;
                    $hist->warehouse = '0000';
                    $hist->partno = 'HIST';
                    $hist->description = "State: $contract->contractstartdate End: $contract->contractenddate";
                    $hist->save();
                }
                else
                {
                    $hist->description = "State: $contract->contractstartdate End: $contract->contractenddate";
                    $hist->save();
                }
            }
        }

        public function actionRenew()
        {
            $model = new Contracts();
            if (isset($_POST))
            {
                $old_data = $this->loadModel($_POST['orginalcontractid']);
                if (ContractUtil::canRenewal($old_data))
                {
                    
                    $model->attributes = $old_data->attributes; //get old record and save it to new record
                    $model->attributes = $_POST;
                    $model->isNewRecord = true;
                    $model->status = 5; //set status to renew    
                 
                    $model->renewalby = Yii::app()->user->getId();
                    if ($model->save())
                    {


                      
                        echo json_encode(array(
                            'success' => true,
                            'msg' => "Saving successful",
                            'contractid' => $model->contractid
                        ));
                    }
                    else
                    {
                        echo json_encode(array(
                            'success' => false,
                            'errors' => $model->getErrors()
                        ));
                    }

                    if ($_POST['importequipment']=="Yes")
                    {
                        ContractUtil::copyEquipment($old_data, $model);
                    }
                }
            }

            Yii::app()->end();
        }
        
        public function actionStaticData($type){
            echo $this->renderPartial('_staticData',array(
                'type'=>$type
            ),true,false);
        }

    }

    